package com.haitaoit.chengquan.module.home.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.baiduservice.LocationInfoModel;
import com.haitaoit.chengquan.base.BaseActivity;
import com.haitaoit.chengquan.module.home.adapter.HotCityAdapter;
import com.haitaoit.chengquan.module.home.model.CityModel;
import com.haitaoit.chengquan.module.home.model.LocationModel;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.utils.Utils;
import com.haitaoit.chengquan.view.MyGridView;
import com.haitaoit.chengquan.view.MyListView;
import com.haitaoit.chengquan.view.sidebar.CharacterParser;
import com.haitaoit.chengquan.view.sidebar.PinyinComparator;
import com.haitaoit.chengquan.view.sidebar.SideBar;
import com.haitaoit.chengquan.view.sidebar.SortAdapter;
import com.haitaoit.chengquan.view.sidebar.SortModel;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class LocationCityActivity extends BaseActivity {
    @ViewInject(R.id.city_hot_list)
    MyGridView city_hot_list;
    @ViewInject(R.id.city_sort_list)
    MyListView city_sort_list;
    @ViewInject(R.id.sl_location)
    ScrollView sl_location;
    @ViewInject(R.id.sidebar)
    SideBar sidebar;
    @ViewInject(R.id.dialog)
    TextView dialog;
    @ViewInject(R.id.now_city)
    TextView now_city;
    @ViewInject(R.id.location_city)
    TextView location_city;
    @ViewInject(R.id.search_city)
    EditText search_city;

    private CharacterParser characterParser;
    private PinyinComparator pinyinComparator;
    private List<SortModel> SourceDateList;
    private SortAdapter adapter;
    private HotCityAdapter hotAdapter;

    private LocationModel location;
    private List<CityModel> hotCity;
    private List<CityModel> allCity;
    private String mLocationCity;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.activity_location_city);
        setTitle_V("定位城市");
        setLeftShow(1, R.mipmap.left);
        backLeft_V();
        ViewUtils.inject(this);

        mLocationCity = PreferenceUtils.getPrefString("choice_city", "");
        if (mLocationCity.contains("省")||mLocationCity.contains("市")){
            String substring = mLocationCity.substring(0, mLocationCity.length() - 1);
            mLocationCity = substring;
        }

        characterParser = CharacterParser.getInstance();
        pinyinComparator = new PinyinComparator();
        sidebar.setTextView(dialog);
        sidebar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                char[] start = "A".toCharArray();
                int sta = start[0];
                char[] end = s.toCharArray();
                int en = end[0];
                int dis = en - sta;
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    // city_sort_list.setSelection(position);
                    View listItem = adapter.getView(0, null, city_sort_list);
                    listItem.measure(0, 0);
                    sl_location.smoothScrollTo(0, (position + dis) *
                            Utils.dip2px(LocationCityActivity.this, 40) + Utils.dip2px(LocationCityActivity.this, 70));
                }
            }
        });

        /* 热门 */
        hotAdapter = new HotCityAdapter(this);
        city_hot_list.setAdapter(hotAdapter);
        city_hot_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//
                String cityName = hotAdapter.getList().get(position).getName();

                PreferenceUtils.setPrefString("choice_city", cityName);
                now_city.setText("当前：" + cityName);
                ToastUtils.showToast("选择城市：" +cityName);
                finish();
            }
        });

        /* 所有 */
        city_sort_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String city = ((SortModel) adapter.getItem(position)).getName();
                PreferenceUtils.setPrefString("location_city", city);
                now_city.setText("当前：" + PreferenceUtils.getPrefString("location_city", ""));
                ToastUtils.showToast("选择城市：" + PreferenceUtils.getPrefString("location_city", ""));
                finish();
            }
        });

        now_city.setText("当前：" + mLocationCity);
        location_city.setText(LocationInfoModel.getInstance().getCity().substring(0, LocationInfoModel.getInstance().getCity().length() - 1));
        httpGetCity();
    }

    @OnClick({R.id.search_citygo})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.search_citygo:
                httpGetCity();
                break;
        }
        super.onClick(v);
    }

    private List<SortModel> filledData(List<CityModel> date) {
        List<SortModel> mSortList = new ArrayList<SortModel>();
        for (int i = 0; i < date.size(); i++) {
            SortModel sortModel = new SortModel();
            sortModel.setName(date.get(i).getName());
            String pinyin = characterParser.getSelling(date.get(i).getName());
            String sortString = pinyin.substring(0, 1).toUpperCase();

            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
            } else {
                sortModel.setSortLetters("");
            }
            mSortList.add(sortModel);
        }
        return mSortList;
    }

    /**
     * 查询城市列表
     */
    private void httpGetCity() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("name", search_city.getText().toString()));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("name", search_city.getText().toString());
        params.addQueryStringParameter("sign", sign);
        HttpUtilsSingle.doGet(this, false, Constant.GetCity_list, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String result = responseInfo.result.toString();
                try {
                    JSONObject json = new JSONObject(result);
                    String ErrCode = json.getString("ErrCode");
                    String ErrMsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    if (Integer.valueOf(ErrCode) == 0) {
                        location = gson.fromJson(Response, LocationModel.class);
                        hotCity = location.getRm_li();
                        allCity = location.getPt_li();

                        hotAdapter.setList(hotCity);
                        hotAdapter.notifyDataSetChanged();

                        SourceDateList = filledData(allCity);
                        Collections.sort(SourceDateList, pinyinComparator);
                        adapter = new SortAdapter(LocationCityActivity.this, SourceDateList);
                        city_sort_list.setAdapter(adapter);
                    } else {
                        ToastUtils.showToast(ErrMsg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                ToastUtils.showToast("数据请求失败，请检查网络！");
            }
        });
    }
}
